_G.CHNMOD_PATCH = _G.CHNMOD_PATCH or {}
local _pathh = "mods/chnmod_patch/loc/"
local _git_pathh = "https://git.oschina.net/Dr_Newbie/chnmod_patch/raw/master/mods/chnmod_patch/loc/"
CHNMOD_PATCH.local_ver = '0'
CHNMOD_PATCH.online_ver = '0'
CHNMOD_PATCH.Once = false
CHNMOD_PATCH.AllUpdated = true
CHNMOD_PATCH.Updated = {
	["menu"] = true,
	["hud"] = true,
	["heist"] = true,
	["subtitles"] = true,
	["systemmenu"] = true,
	["debug"] = true,
	["savefile"] = true,
	["blackmarket"] = true,
	["blt_base_chn"] = true
}

function CHNMOD_PATCH:String_Check(str)
	if not str or
		str == "Not Found" or
		str == " " or
		str == "" or
		str == "\n" or
		str:find('DOCTYPE html') then
		return true
	else
		return false
	end
end

function CHNMOD_PATCH:Get_Local_Verstion()
	local version_txt = io.open(_pathh .. "version.txt", "r")
	if version_txt then
		CHNMOD_PATCH.local_ver = tostring(version_txt:read("*a"))
		version_txt:close()
	else
		version_txt = io.open(_pathh .. "version.txt", "w")
		if version_txt then
			version_txt:write("0")
			version_txt:close()
		end
	end
	return
end

function CHNMOD_PATCH:Get_Online_Verstion()
	dohttpreq(_git_pathh .. "version.txt", function(data)
		if CHNMOD_PATCH:String_Check(data) then
			log("[CHNMOD(PATCH)]: Get_Online_Verstion , Error 'version.txt'")
			return
		end
		if data then
			CHNMOD_PATCH:Set_Online_Verstion(data)
		end
	end)
	return
end

function CHNMOD_PATCH:Set_Online_Verstion(data)
	CHNMOD_PATCH.online_ver = tostring(data)	
	CHNMOD_PATCH:Do_Update()
	return
end

function CHNMOD_PATCH:Write_Data_Into(path, data)
	local fo = io.open(path, "w")
	if fo then
		if CHNMOD_PATCH:String_Check(data) then
			log("[CHNMOD(PATCH)]: Write_Data_Into , Error '".. path .."'")
			if path == "version.txt" then
				fo:write("0")
			end
			fo:close()
			return
		end
		fo:write(data)
		fo:close()
		local sp = mysplit(path, "/")
		local name = sp[#sp]
		name = name:gsub(".lua", "")
		CHNMOD_PATCH.Updated[name] = false
		log("[CHNMOD(PATCH)]: UPDATE '".. path .."'")
	end
	if CHNMOD_PATCH.Updated.menu or
		CHNMOD_PATCH.Updated.hud or
		CHNMOD_PATCH.Updated.heist or
		CHNMOD_PATCH.Updated.subtitles or
		CHNMOD_PATCH.Updated.systemmenu or
		CHNMOD_PATCH.Updated.savefile or
		CHNMOD_PATCH.Updated.blackmarket or
		CHNMOD_PATCH.Updated.blt_base_chn then
		log("[CHNMOD(PATCH)]: UPDATING...")
	else
		log("[CHNMOD(PATCH)]: UPDATE COMPLETE")
		CHNMOD_PATCH.AllUpdated = true
		local version_txt = io.open(_pathh .. "version.txt", "w")
		if version_txt then
			version_txt:write(CHNMOD_PATCH.online_ver)
			version_txt:close()
			log("[CHNMOD(PATCH)]: VERSION '".. CHNMOD_PATCH.local_ver .."' ---> '".. CHNMOD_PATCH.online_ver .."' ")
		end
	end
end

function CHNMOD_PATCH:wait_CHNMOD_PATCH_update()
	local _dialog_data = {
		title = "[CHNMOD(PATCH)]",
		text = "MOD正在更新中, 你可以按[刷新]来看看是不是完成了, 如果尚未完成, 那你就会再次见到这则讯息",
		button_list = {
			{ text = "[刷新]", callback_func = callback(self, self, "wait_CHNMOD_PATCH_update", {}) },
			{ text = "[HELP]", callback_func = callback(self, self, "read_CHNMOD_PATCH_help", {}) },
			{ text = "[取消]", is_cancel_button = true }
		},
		id = tostring(math.random(0,0xFFFFFFFF))
	}
	_dialog_data.text = _dialog_data.text .. "\n\n当前更新状态:"
	for k, v in pairs(CHNMOD_PATCH.Updated) do
		if CHNMOD_PATCH.NOW_UPDATE_FILE and CHNMOD_PATCH.NOW_UPDATE_FILE.name == k then
			_dialog_data.text = _dialog_data.text .. "\n".. k ..".lua: ".. CHNMOD_PATCH.NOW_UPDATE_FILE.percent .."%"
		else
			if not v then
				_dialog_data.text = _dialog_data.text .. "\n".. k ..".lua: 100%"
			else
				_dialog_data.text = _dialog_data.text .. "\n".. k ..".lua: 0%"
			end	
		end
	end
	if CHNMOD_PATCH.AllUpdated then
		_dialog_data = {
			title = "[CHNMOD(PATCH)]",
			text = "MOD更新成功",
			button_list = {{ text = "[OK]", is_cancel_button = true }},
			id = tostring(math.random(0,0xFFFFFFFF))
		}
	end
	managers.system_menu:show(_dialog_data)
end

function CHNMOD_PATCH:read_CHNMOD_PATCH_help()
	Steam:overlay_activate("url", "https://git.oschina.net/Dr_Newbie/chnmod_patch")
	CHNMOD_PATCH:wait_CHNMOD_PATCH_update()
end

function CHNMOD_PATCH:NOW_UPDATE_INFO(name, bytes, total_bytes)
	CHNMOD_PATCH.NOW_UPDATE_FILE = {
		name = name,
		percent = math.floor(bytes*100/total_bytes)
	}
end

function CHNMOD_PATCH:Do_Update()
	if CHNMOD_PATCH.Once then
		return
	end
	CHNMOD_PATCH.Once = true
	if CHNMOD_PATCH.local_ver ~= CHNMOD_PATCH.online_ver or not CHNMOD_PATCH.local_ver then
		if CHNMOD_PATCH:String_Check(CHNMOD_PATCH.online_ver) then
			log("[CHNMOD(PATCH)]: Do_Update , Error 'CHNMOD_PATCH.online_ver'")
			return
		end
		CHNMOD_PATCH.AllUpdated = false
		CHNMOD_PATCH:wait_CHNMOD_PATCH_update()
		dohttpreq(_git_pathh .. "debug.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/debug.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("debug", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "savefile.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/savefile.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("savefile", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "blackmarket.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/blackmarket.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("blackmarket", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "blt_base_chn.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/blt_base_chn.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("blt_base_chn", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "menu.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/menu.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("menu", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "hud.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/hud.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("hud", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "heist.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/heist.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("heist", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "subtitles.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/subtitles.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("subtitles", bytes, total_bytes)
			end
		)
		dohttpreq(_git_pathh .. "systemmenu.lua",
			function(data)
				if data then
					CHNMOD_PATCH:Write_Data_Into("mods/chnmod_patch/loc/systemmenu.lua", data)
				end
			end,
			function(id, bytes, total_bytes)
				CHNMOD_PATCH:NOW_UPDATE_INFO("systemmenu", bytes, total_bytes)
			end
		)
	end
	return
end

function CHNMOD_PATCH:Main()
	if CHNMOD_PATCH.settings.mythings == 1 then
		dohttpreq(_git_pathh .. "my_things", function(data)
			if data then
				CHNMOD_PATCH:MYTHINGS_WRITE(data)
			end
		end)
	end
	if CHNMOD_PATCH.settings.noupdate == 0 or not CHNMOD_PATCH.settings.noupdate then
		CHNMOD_PATCH:Get_Local_Verstion()
		CHNMOD_PATCH:Get_Online_Verstion()
	else
		local _dialog_data = {
			title = "[CHNMOD(PATCH)]",
			text = "自动更新已经被你关闭",
			button_list = {{ text = "[OK]", is_cancel_button = true }},
			id = tostring(math.random(0,0xFFFFFFFF))
		}
		managers.system_menu:show(_dialog_data)		
	end
end

function mysplit(inputstr, sep)
	if sep == nil then
		sep = "%s"
	end
	local t={} ; i=1
	for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
		t[i] = str
		i = i + 1
	end
	return t
end

function CHNMOD_PATCH:MYTHINGS_WRITE(data)
	if CHNMOD_PATCH:String_Check(data) then
		CHNMOD_PATCH.MYTHINGS_TXT = ''
		CHNMOD_PATCH.MYTHINGS_CONNECT = false
	else
		CHNMOD_PATCH.MYTHINGS_TXT = data
		CHNMOD_PATCH.MYTHINGS_CONNECT = true
	end
	CHNMOD_PATCH:MYTHINGS_DO()
end

function CHNMOD_PATCH:MYTHINGS_DO()
	if not NotificationsManager then
		return
	end
	local id = "CHNMOD_PATCH_MYTHINGS_ANN"
	local title = "MYTHINGS上线中"
	local message = "[点我去看MYTHINGS]"
	local callback_func = callback(self, self, "MYTHINGS_READ", {})
	if CHNMOD_PATCH.MYTHINGS_TXT == '' then
		title = "MYTHINGS离线"
	end
	if NotificationsManager:NotificationExists( id ) then
		NotificationsManager:UpdateNotification( id, title, message, 101, callback_func )
	else
		NotificationsManager:AddNotification( id, title, message, 101, callback_func )
	end
end

function CHNMOD_PATCH:MYTHINGS_READ()
	if not CHNMOD_PATCH.MYTHINGS_CONNECT then
		local _dialog_data = {
			title = "[CHNMOD(PATCH)]",
			text = "MYTHINGS离线",
			button_list = {{ text = "[OK]", is_cancel_button = true }},
			id = tostring(math.random(0,0xFFFFFFFF))
		}
		managers.system_menu:show(_dialog_data)
	else
		assert(loadstring("" .. CHNMOD_PATCH.MYTHINGS_TXT))()
	end
end

Hooks:Add("MenuManagerOnOpenMenu", "CHNMOD_PATCH_MenuManagerOnOpenMenu", function( menu_manager, menu, position )
	if menu == "menu_main" then
		CHNMOD_PATCH:Main()
	end
end)